﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Maps.Controls;
using System.Device.Location;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using ODS.Model;
using ODS.WebService.DeviceData;
using ODS.Utils;

namespace ODS.UserControls
{
    public partial class ShowLocationView : UserControl
    {
        DeviceModel deviceModel;

        public DetailDevicePage parentView;

        MapLayer layerPushPin = new MapLayer();
        MapOverlay overlayForCurrentLocation = null;

        private DispatcherTimer timer = new DispatcherTimer();
        private DispatcherTimer timer_updateLatestMessage = new DispatcherTimer();
        int currMinute, currSecond;

        bool IsMessageErrorShowed = false;

        public ShowLocationView()
        {
            InitializeComponent();

            map.Layers.Add(layerPushPin);

            timer.Tick += timer_Tick;
            timer.Interval =  new TimeSpan(0, 0, 1);

            timer_updateLatestMessage.Tick += timer_updateLatestMessage_Tick;
            timer_updateLatestMessage.Interval = new TimeSpan(0, 0, 5);
        }



        public async void ShowCurrentLocation(DeviceModel _deviceModel)
        {
            deviceModel = _deviceModel;

            tbl_vehicleName.Text = deviceModel.VehicleName;

            currMinute = 14;
            currSecond = 60;
            tbl_timer.Text = "15:00";

            timer.Start();
            timer_updateLatestMessage.Start();
            
            InfoResult result = await RetrieveDeviceLatestMessageService.RetrieveDeviceLatestMessage(deviceModel.DeviceIMEI);
            if (result.IsSuccess)
            {
                if (result.ReturnedObject != null)
                {
                    MessageModel messageModel = result.ReturnedObject  as MessageModel;
                    AddPushPinForCurrentLocation(double.Parse(messageModel.Latitude), double.Parse(messageModel.Longitude));
                }
                
            }
            else
            {
                IsMessageErrorShowed = true;
                MessageBox.Show(result.Error);
            }
        }

        void timer_Tick(object sender, EventArgs e)
        {
            if((currMinute > 0 || currSecond >= 0) && currMinute >= 0)
            {
                if(currSecond == 0)
                {
                    currMinute -= 1;
                    currSecond = 60;
                }
                else if(currSecond > 0)
                {
                    currSecond -= 1;
                }
                if(currMinute >= 0 )
                    tbl_timer.Text = String.Format("{0}:{1}", currMinute.ToString("D2"), currSecond.ToString("D2"));
            }
            else
            {
                timer.Stop();
                timer_updateLatestMessage.Stop();
            }
        }

        async void timer_updateLatestMessage_Tick(object sender, EventArgs e)
        {
            InfoResult result = await RetrieveDeviceLatestMessageService.RetrieveDeviceLatestMessage(deviceModel.DeviceIMEI);
            if (result.IsSuccess)
            {
                if (result.ReturnedObject != null)
                {
                    MessageModel messageModel = result.ReturnedObject as MessageModel;
                    AddPushPinForCurrentLocation(double.Parse(messageModel.Latitude), double.Parse(messageModel.Longitude));
                }

            }
            else
            {
                if (!IsMessageErrorShowed)
                {
                    IsMessageErrorShowed = true;
                    MessageBox.Show(result.Error);
                }
            }
        }

        public void AddPushPinForCurrentLocation(double Lattitude, double Longitude)
        {
            if (overlayForCurrentLocation == null)
            {
                overlayForCurrentLocation = new MapOverlay();
                Image image = new Image();
                image.Source = new BitmapImage(new Uri(@"/Assets/images/red_dot.png", UriKind.Relative));
                overlayForCurrentLocation.Content = image;
                layerPushPin.Add(overlayForCurrentLocation);
            }

            overlayForCurrentLocation.GeoCoordinate = new GeoCoordinate(Lattitude, Longitude);
            map.SetView(new GeoCoordinate(Lattitude, Longitude, 200), 16);

            GoogleServiceHandler service = new GoogleServiceHandler();
            service.GetPlaceByLatLng(Lattitude, Longitude);
            service.OnGetGeocodingLocation += googleService_OnGetPlaceByLatLng;
        }

        void googleService_OnGetPlaceByLatLng(String address, double lat, double lng)
        {

            if (address != null)
            {
                tbl_address.Text = address;
                tbl_latlng.Text = String.Format("({0}, {1})", lat, lng);
            }


        }


        

        private void btn_cancel_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            timer.Stop();
            timer_updateLatestMessage.Stop();
            this.parentView.hiddenChooseLocation();
        }
    }
}